package uit.mmt02.activity;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;
import uit.mmt02.R;
import uit.mmt02.dataAccess.DB_EmailLoginManager_Adapter;
import uit.mmt02.dataAccess.db_email;
import uit.mmt02.doituong.OneMail;
import uit.mmt02.doituong.attach;
import uit.mmt02.doituong.showToast;
import uit.mmt02.mailControl.GmailControl;
import uit.mmt02.mailControl.HotmailControl;
import uit.mmt02.mailControl.YahooControl;
import uit.mmt02.xuly.ConvertMessageToList;
import uit.mmt02.xuly.XuLyChuoi;
import uit.mmt02.xuly.XulySql;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;

public class readmailActivity extends Activity
{
	showToast st ;
//	final static String KEY_SUB = "SUB";
//	final static String KEY_FROM = "FROM";
//	final static String KEY_TO = "TO";
//	final static String KEY_TIME = "TIME";
//	final static String KEY_BODY = "BODY";
//	final static String KEY_FAVORITE = "FAVORITE";
//	final static String KEY_BUNDLE = "BUNDLE";
	
	final static String KEY_STT = "_stt";
	final static String KEY_DB = "_key_db";
	final static String KEY_MESS = "message";
	final static String KEY_USERNAME = "username";
	final static String KEY_PASSWORD = "password";
	final static String KEY_LOAIEMAIL = "loai_email";
	final static String KEY_STR_ATTACH = "chuoi_attach";
	
	TextView txt_int_att, txtstt,txtsub, txtfrom, txtto, txttime, txtbody;
    CheckBox cb_favorite;
    ImageButton btn_att_view;
    ImageButton img_int_att, img_next, img_back, img_attach, img_encrypt, img_voice, img_decrypt;
//    ListView lv_attach;
//    ArrayAdapter<String>adapter;
    //
    int stt;
    db_email mydb;
    XulySql xulysql;
    XuLyChuoi xulychuoi;
    String db_name;
    String tag = "readmailActivity";
    List<String>list_str_attach;
    
    //
    List<attach>list;
//    ArrayAdapter<attach>adapter;
    
    //
    OneMail omG;
    //
    String username;
    String password;
    Message []mess;
    ConvertMessageToList cv;
    XuLyChuoi xlchuoi ;
	String loai_email;
    GmailControl g;
    YahooControl y;
    HotmailControl h;
    DB_EmailLoginManager_Adapter db_login;
    String str_att;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    
	    
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.read_mail); 
		st = new showToast(getBaseContext());
		stt = getIntent().getIntExtra(KEY_STT, 0);
		db_name = getIntent().getStringExtra(KEY_DB);
		username = getIntent().getStringExtra(KEY_USERNAME);
		Log.v(tag, "username : " + username);
		db_login = new DB_EmailLoginManager_Adapter(this);
		password = db_login.db_getpassword(username);
		txtstt = (TextView)findViewById(R.id.txt_readmail_stt);
		txtsub = (TextView)findViewById(R.id.txt_readmail_sub);
		txtfrom = (TextView)findViewById(R.id.txt_readmail_from);
		txtto = (TextView)findViewById(R.id.txt_readmail_to);
		txttime = (TextView)findViewById(R.id.txt_readmail_time);
		txtbody = (TextView)findViewById(R.id.txt_readmail_body);
		txt_int_att = (TextView)findViewById(R.id.txt_readmail_int_att);
		//
		//
		img_next = (ImageButton)findViewById(R.id.img_readmail_next);
		img_back = (ImageButton)findViewById(R.id.img_readmail_back);
		img_attach = (ImageButton)findViewById(R.id.img_readmail_att);
		img_encrypt = (ImageButton)findViewById(R.id.img_readmail_encrypt);
		img_voice = (ImageButton)findViewById(R.id.img_readmail_voice);
		img_decrypt = (ImageButton)findViewById(R.id.img_readmail_decrypt);
		img_int_att = (ImageButton)findViewById(R.id.img_readmail_int_attach);
		cb_favorite = (CheckBox)findViewById(R.id.cb_readmail_favorite);
		//
//		lv_attach = (ListView)findViewById(R.id.lv_readmail_att);
//		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice);
//		list = new ArrayList<attach>();
//		adapter = new attach_adapter(this, list);
//		lv_attach.setAdapter(adapter);
		//
		mydb = new db_email(this, db_name);
		xulysql = new XulySql();
		xulychuoi = new XuLyChuoi();
		if(stt != 0)
		{
			read_mail(stt);
		}
		
		//
		g = new GmailControl(username, password);
		y = new YahooControl(username, password);
		h = new HotmailControl(username, password);
		cv = new ConvertMessageToList();
		xlchuoi = new XuLyChuoi();
		loai_email = xlchuoi.kt_loai_email_login(username);
		show_int_att();
		//
		
	};
	
	public void btn_onClick(View v)
	{
		Button  btn = (Button)v;
		switch (btn.getId()) {
		default:
			break;
		}
	}
	

	public void img_onClick(View v)
	{
		ImageButton img = (ImageButton)v;
		switch (img.getId()) {
		case R.id.img_readmail_int_attach:
			Intent i_att = new Intent(this, attach_download_Activity.class);
			i_att.putExtra(KEY_USERNAME, username);
			i_att.putExtra(KEY_PASSWORD, password);
			i_att.putExtra(KEY_LOAIEMAIL, loai_email);
			i_att.putExtra(KEY_STR_ATTACH, str_att);
			i_att.putExtra(KEY_STT, stt);
			startActivity(i_att);
			break;
		case R.id.img_readmail_reply:
			break;
		case R.id.img_readmail_forward:
			st.showmess("4word");
			break;
	
		case R.id.img_readmail_att:
			break;
		case R.id.img_readmail_decrypt:
			st.showmess("giai ma");
			break;
		case R.id.img_readmail_next:
//			remove_list();
//			adapter.notifyDataSetChanged();
			stt ++;
//			img_back.setVisibility(ImageButton.VISIBLE);
			img_back.setEnabled(true);
			if(stt <= 10)
			{
				read_mail(stt);
			}
			else
			{
				img_next.setEnabled(false);
//				img_next.setVisibility(ImageButton.GONE);
			}
			show_int_att();
			break;
		case R.id.img_readmail_back:
//			img_next.setVisibility(ImageButton.VISIBLE);
			img_next.setEnabled(true);
			stt --;
			if(stt > 0 )
			{
				read_mail(stt);
			}
			else
			{
				img_back.setEnabled(false);
//				img_back.setVisibility(ImageButton.GONE);
			}
			show_int_att();
			break;

		default:
			break;
		}
	}
	
	public void read_mail(int _stt)
	{
		
		try
		{
			mydb.open();
			Cursor mCursor = mydb.query_get_by_stt(stt);
			OneMail mail = xulysql.cv_get_by_stt(mCursor);
			mCursor.close();
			mydb.close();
			txtstt.setText("---- "+String.valueOf(mail.getId())+ "----");
			txtsub.setText(getResources().getString(R.string.mail_sub) + mail.getSub());
			txtfrom.setText(getResources().getString(R.string.mail_from) +mail.getFrom());
			txtto.setText(getResources().getString(R.string.mail_to)+mail.getTo2());
			txttime.setText(mail.getDateSend());
			txtbody.setText(mail.getBody());
			list_str_attach = new ArrayList<String>();
			str_att = "";
			if(mail.isFlagAttach())
			{
				img_attach.setVisibility(ImageButton.VISIBLE);
//				img_save.setVisibility(ImageButton.VISIBLE);
				//thuc hien add list add vao
				str_att = mail.getStr_attach2();
				Log.v(tag, str_att);
				list_str_attach = xulychuoi.getList_str_attach(str_att);
//				attach att = null;
//				for(String str1 : list_str_attach)
//				{
//					if(!str1.equals("") && str1!= null )
//						att = new attach(str1, true);
//						Log.v(tag, "add att " + str1);
//						list.add(att);
//				}
//				adapter.notifyDataSetChanged();
			}
			
			else
			{
				img_attach.setVisibility(ImageButton.GONE);
//				img_save.setVisibility(ImageButton.GONE);
//				int i_list = list.size();
//				List<Integer>i_del = new ArrayList<Integer>();
//				
//				for(int i = i_list - 1 ; i >= 0; i --)
//				{
//					attach o3 = list.get(i);
//					if(o3.isCheck()) // neu dc check
//					{
//						Log.v(tag, "Tien hanh delete..." + i);
//						i_del.add(i);
//					}
//				}
//				for(int i : i_del)
//				{
//					list.remove(i);
//				}
//				adapter.notifyDataSetChanged();
			}
			
			if(mail.isFlagEncrypt())
			{
				img_encrypt.setVisibility(ImageButton.VISIBLE);
				img_decrypt.setVisibility(ImageButton.VISIBLE);
			}
			else
			{
				img_encrypt.setVisibility(ImageButton.GONE);
				img_decrypt.setVisibility(ImageButton.GONE);
			}
			
			if(mail.isFlagVoice())
				img_voice.setVisibility(ImageButton.VISIBLE);
			else
				img_voice.setVisibility(ImageButton.GONE);
			
			if(mail.isFlagFavorite())
				cb_favorite.setChecked(true);
			else
				cb_favorite.setChecked(false);
				
					
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi read mail " + e.toString());
		}
		
	}
	
	public void remove_list()
	{
		try
		{
			
			for(int i = list.size() -1 ; i >= 0; i--)
			{
				list.remove(i);
				Log.v(tag, "remove " + i);
			}
//			adapter.notifyDataSetChanged();
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "ko the remove all");
		}
	}
	
	public void save_att()
	{
		get_loai_mail();
		
		try
		{
			int i_down =  mess.length - stt;
//			Log.v(tag, mess[i_down].getSubject().toString());
			for(int i = 0 ; i < list.size(); i++)
			{
				if(list.get(i).isCheck())
				{
					//save con i
					Log.v(tag, "vao save _att");
					cv.Download_by_name(mess, i_down , i);
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Err save att " +e.toString());
		}
		
	}
	public void open_forder_download()
	{
		try
		{
			AlertDialog.Builder buider = new AlertDialog.Builder(this);
			buider.setMessage("Open forder Download ...");
			buider.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			buider.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					return;
				}
			});
			
			AlertDialog alert = buider.create();
			alert.show();
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "err open_download " +e.toString());
		}
	}
	
	public void get_loai_mail()
	{
		if(loai_email.startsWith("gmail"))
			mess = g.getmail();
		else if(loai_email.startsWith("yahoo"))
		{
			mess = y.getmail();
		}	//
		else if(loai_email.startsWith("hotmail"))
		{
			//
			mess = h.getmail();
		}
	}
	
	
	public void show_int_att()
	{
		txt_int_att.setText(String.valueOf(list_str_attach.size()));
		if(list_str_attach.size() == 0)
			img_int_att.setEnabled(false);
		else
			img_int_att.setEnabled(true);
	}
	
	//tao menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater m_MenuInflater = getMenuInflater();
		m_MenuInflater.inflate(R.menu.menu_read_mail, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.item_readmail_newmail:
			startActivity(new Intent(this, newmailActivity.class));
			break;

		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
}
